<template>
  <!-- 问题信息弹窗 -->
  <dialog-form v-bind="$attrs" v-on="$listeners" ref="dialogForm" :form="dialogForm" :editModel="dialogEditModel" @changeRules="changeRules" 
    :width="1000" :formList="dialogFormList" :visible.sync="visible" :isEmit="false"
    :class="[isFlagcheckType ? 'isFlagcheckType' : '',bcRules?'deFlagcheckType':'',pubDialogForm?'pubDialogForm':'',wtjbClassName]"   
    @confirm="(e) => $emit('handleConfirm', e)">
    <!-- isFlagcheckType 为管理行为，deFlagcheckType整改单位 stCsClassName为补充的一般问题，xwZlClassName补充的管理行为一般问题-->
    <template slot="coordinate" slot-scope="scoped">
      <span
        v-if="scoped.data.form.problem && scoped.data.form.problem.coordinate && scoped.data.form.problem.coordinate.length"
        class="del_btn">已选</span>
      <a-button class="ml12" :loading="btnLoading" type="primary" icon="paper-clip"
        @click="handleChoose(scoped.data.form)">选择具体位置</a-button>
      <!-- 打点图 -->
      <PreView :isEdit="true" :isDownload="false" :pointer.sync="scoped.data.form.coordinate"
        :preview-image="previewImage" :visible.sync="previewVisible"
        @getPointer="(e) => handlePoints(e, scoped.data.form)" />
    </template>
  </dialog-form>
</template>

<script>
import { scoringType } from '@/api/quality/quality' // 质量api
import { getNodeById } from '@/api/complaint' // 维保api
import office from '@/api/office/asset' // 办公api
import ASelectOrgPeople from '@/components/Select/ASelectOrgPeople' // 人员选择器
import Selector from '@/components/Select/Selector' // 人员选择器
import DialogForm from '@/components/DialogForm' // 添加问题弹窗
import SelectATtree from '@/components/Select/SelectATtree' // 通用搜索树
import SelectTreeDistrict from '@/components/Select/SelectTreeDistrict' // 检查区域
import SelectProblemTypeTree from '@/components/Select/SelectProblemTypeTree' // 质量问题描述
import SelectDutyArea from '@/components/Select/SelectDutyArea' // 整改单位
import PreView from '@/components/PreView' // 检查问题具体位置（打点）
import { projectType,subItem} from '@/api/quality/currency' // api
import SelectProjectType from '@/components/Select/SelectProjectType' // 工程类别
export default {
  name: 'DialogProblem',
  components: {
    DialogForm,
    PreView,
    SelectATtree
  },
  props: {
    // 弹窗操作类型：U 新增；E 编辑
    dialogEditModel: {
      type: String,
      default: () => 'U'
    },
    // 外部表单
    dialogForm: {
      type: Object,
      default: () => ({})
    },
    //选中的受检单位岗位信息
    postData: {
      type: Object,
      default: () => { }
    },
  },
  data() {
    return {
      btnLoading: false, // 选择具体位置按钮加载控件
      visible: false, // 弹窗控件
      previewVisible: false, // 打点图弹窗控件
      previewImage: [], // 打点图
      options: [], // 工程品质类型列表
      rectifierCompany: {}, // 整改单位业务对象
      fbfxTreeData:[],  //分部分项数据data
      productType:[],  //工程类别数据
      tageCode:null, //受检单位的code 
      isFlagcheckType:false,   //是否是 false工程实体和措施 或 true管理行为和资料  
      checkTypeId:null,  // 声明一个检查类别，用于监听
      bcRules:false, // 业务待办补充的校验
      pubDialogForm:true,
      isBcRules:false, //是否是补充
      isManagement:false, // 是否是管理行为
    }
  },
  created() {
    //  非项目级岗位，则获取专项治理类型和新六项措施类型
    this.$currentPost()?.code !== 'PD' && this.getType()
  },
  watch:{
   visible(e) {
     this.tageCode = this.dialogForm?.tageCode;
     if(this.dialogForm.checkTypeName=='管理行为' || this.dialogForm.checkTypeName=='工程资料'){  //工程资料和管理行为要自动带出
       this.$set(this.$refs.dialogForm.forms,'areaName', this.dialogForm.inspectedUnitName)  //inspectedUnitId
      //  this.$set(this.dialogForm,'areaId', this.dialogForm.inspectedUnitId)
     }  
    },
   	'dialogForm.projectTypeId'(val) { 
      this.getSubItemData(val) 
		// 代码实现
	},
  checkTypeId(val){ //监听兹定于检查类别清空对应的数据
      this.pubDialogForm = true;
      if(val){
         this.$set(this.$refs.dialogForm.forms,'rectifierId',null)   //清空 整改人
         this.$set(this.$refs.dialogForm.forms,'dutyId',null)   //清空 责任人
         this.$set(this.$refs.dialogForm.forms,'reCheckId',null)   //清空 复查人
         this.$set(this.$refs.dialogForm.forms,'problemTypeId',null)  // 清空 质量问题描述
         this.$set(this.$refs.dialogForm.forms,'areaId',null)  // 清空 整改单位
         this.$set(this.$refs.dialogForm.forms, 'subProjectId', null)  // 清空分部分项
         this.$set(this.$refs.dialogForm.forms,'respAreaId',null)   //清空 检查区域
         this.$set(this.$refs.dialogForm.forms,'newRespAreaId',null)   //清空 检查区域
         delete this.$refs.dialogForm.forms.sendUserIds //清空 抄送人
         this.fbfxTreeData = [];
         this.$set(this.$refs.dialogForm.forms,'projectTypeId',null)   //清空 工程类别
      }
    },
   isFlagcheckType(val){
    if(val){
      this.$set(this.$refs.dialogForm.forms,'areaName', this.dialogForm.inspectedUnitName)
      this.$emit('emptyRules',val)
      //this.getProductType(this.dialogForm.projectId); // 获取工程类别数据
      this.productTypeId = this.dialogForm.projectId;
    }else{
      this.fbfxTreeData = [];
    }      
   } 
  },
  computed: {
    // 弹窗配置项
    dialogFormList() {
      return [
        // 弹窗表单配置
        {
          keyName: 'checkTypeId',
          label: '检查类别',
          type: Selector,
          attrs: {
            selectType: '56',
            jobLevel: this.postData?.tageCode || this.dialogForm.tageCode     // this.dialogForm.tageCode 是补充传的code，
          },
          getOption: (obj) => {
            this.isFlagcheckType = obj?.name=='工程资料' || obj?.name=='管理行为';
            this.isManagement = obj?.name=='管理行为'?true:false;
            this.$emit('changeCheckTypeId',this.isFlagcheckType)
            this.$refs.dialogForm.forms.checkTypeCode = obj?.code || ''
            this.$refs.dialogForm.forms.checkTypeName = obj?.name || ''
          },
          input: (e) => {
            if (e) {
              this.checkTypeId = e;
            }
          }
        },
        {
          keyName: 'typeId',
          label: '检查类型',
          type: Selector,
          attrs: {
            selectType: '0',
            isDefault: !this.$refs.dialogForm?.forms?.typeId?true:false,
            isDefaultTypeId:!this.$refs.dialogForm?.forms?.typeId?true:false,
            attr: {
              code: '1',
            }
          },
        },
        {
          keyName: 'respAreaId',
          label: '检查区域',
          type: SelectTreeDistrict,
          hidden: !this.visible,
          attrs: {
            id: this.dialogForm.projectId,
            isShowSearch: false,
            isFirstNode: true,
            deleteProjectId:true,
            finalNode:true,
          },
          change: (value, label) => {
            this.$set(this.$refs.dialogForm.forms,'newRespAreaId',value) //新加一个字段用于联动
            this.$refs.dialogForm.forms.respAreaName = label[0] || ''
            // 重置整改人和责任人列表及表单
            this.rectifierCompany = {}
            this.$set(this.$refs.dialogForm.forms, 'rectifierId', void 0)
            this.$set(this.$refs.dialogForm.forms, 'dutyId', void 0)
            this.$set(this.$refs.dialogForm.forms, 'coordinate', void 0)
            if(!this.isFlagcheckType){
               this.$set(this.$refs.dialogForm.forms, 'subProjectId', null)  // 清空分部分项
               this.fbfxTreeData = [];
            }
            //this.fbfxTreeData = []; //清空分部分项数据
            if (!this.$refs.dialogForm.forms.problem) {
              this.$set(this.$refs.dialogForm.forms, 'problem', { coordinate: void 0 })
            } else {
              this.$set(this.$refs.dialogForm.forms.problem, 'coordinate', void 0)
            }
          }
        },
        {
          keyName: 'areaName',
          label: '整改单位',
          type: 'BaseInput',
          hidden:!this.isFlagcheckType, 
          disabled: true,
        },
        {
          keyName: 'areaId',
          label: '整改单位',
          type: SelectDutyArea,
          hidden: !this.visible || this.isFlagcheckType,
          placeholder:!this.isFlagcheckType?"请先选择检查区域":'请选择',
          attrs: {
            keyValue: 'newRespAreaId',
            isEdit: this.dialogEditModel === 'E',
            isClear: this.dialogEditModel !== 'E',
            replaceFilds: {
              id: 'id',
              name: 'name'
            }
          },
          change: (e) => {
            // 重置整改人和责任人列表及表单
            this.rectifierCompany = {}
            this.$set(this.$refs.dialogForm.forms, 'rectifierId', void 0)
            this.$set(this.$refs.dialogForm.forms, 'dutyId', void 0)
            this.$set(this.$refs.dialogForm.forms, 'subProjectId', null)
          },
          selectChange: (e) => {
            this.fbfxTreeData = [e.item];
            this.pubDialogForm = false;
            this.$set(this.$refs.dialogForm.forms, 'projectTypeId', e.projectConstructionTypeId)   //工程实体和工程措施
            if (!this.$refs.dialogForm.forms.problem) {
              this.$set(this.$refs.dialogForm.forms, 'problem', { rectifierCompanyId: e?.subContractorId || '', rectifierCompanyName: e?.subContractor?.name || '' })
            } else {
              this.$set(this.$refs.dialogForm.forms.problem, 'rectifierCompanyId', e?.subContractorId || '')
              this.$set(this.$refs.dialogForm.forms.problem, 'rectifierCompanyName', e?.subContractor?.name || '')
            }
            this.$refs.dialogForm.forms.rectifierCompanyName = e?.subContractor?.name || ''
            this.$refs.dialogForm.forms.rectifierCompanyId = e?.subContractorId || ''
            this.rectifierCompany = e
          },
        },
        // {
        //   keyName: 'projectTypeId1',
        //   label: '工程类别',
        //   type: 'a-select',
        //   data: this.productType || [],
        //   hidden:!this.isFlagcheckType, 
        //   placeholder:'请选择222',
        //   replaceFields: {
        //     value: 'projectTypeId',
        //     label: 'projectTypeName'
        //   },
        //  change: (e) => {
        //     // this.$set(this.$refs.dialogForm.forms, 'subProjectId', null)  // 清空分部分项
        //      this.$set(this.$refs.dialogForm.forms,'problemTypeId',null) // 清空质量问题描述
        //      this.getSubItemData(e) 
        //   }
        // },
        {
          keyName: 'projectTypeId',
          label: '工程类别',
          type: SelectProjectType,
          hidden:!this.isFlagcheckType, 
          attrs:{
            showStop:false,
            id:this.productTypeId,
          },
          getOptions:(e)=>{
              if(!this.dialogForm.projectTypeId){
              // this.$refs.dialogForm.forms.projectTypeId = e[0]?.projectTypeId //设置工程类别默认值
              // this.getSubItemData(e[0]?.projectTypeId)  ////获取工程资料或管理行为分部分项
            }
          },
         change: (e) => {
             this.$set(this.$refs.dialogForm.forms, 'subProjectId', null)  // 清空分部分项
             if(!this.isManagement){
                this.$set(this.$refs.dialogForm.forms,'problemTypeId',null) // 清空质量问题描述
             }
              if(e){
                  this.getSubItemData(e) 
                }else{
                  this.fbfxTreeData = [];
                }
          }
        },
        {
          keyName: 'subProjectId',
          label: '分部分项',
          placeholder:!this.isFlagcheckType?"请先选择整改单位":'请选择',
          type: SelectATtree,
          hidden: !this.visible,
          attrs: {
            treeData: this.fbfxTreeData,
          },
          change: (value, label) => {
            let flag = this.$refs.dialogForm.forms.checkTypeName == '管理行为';
            !flag && this.$set(this.$refs.dialogForm.forms, 'problemTypeId', null); //管理行为不清除
            if (label[0]) {
              this.$refs.dialogForm.forms.subProjectName = label[0] || ''
              this.$refs.dialogForm.forms.subProjectId = value
              this.$set(this.dialogForm, 'subProjectId', value)
            } else {
              !flag && this.$set(this.$refs.dialogForm.forms, 'problemTypeId', null); //管理行为不清除
            }
          },
        },
        {
          keyName: 'checkDescribe',
          label: '具体部位',
          type: 'BaseInput'
        },
        {
          keyName: 'problemTypeId',
          label: '问题描述',
          type: SelectProblemTypeTree,
          hidden: !this.visible,
          attrs: {
            subProjectId: this.$refs.dialogForm?.forms.subProjectId,
            checkTypeId:this.$refs.dialogForm?.forms.checkTypeId,
            projectTypeId:this.$refs.dialogForm?.forms.projectTypeId,
            isDisabled: true,
            isManagement:this.isManagement,
            isFlagcheckType:this.isFlagcheckType
          },
          change: (name, option) => {
            this.$refs.dialogForm.forms.problemTypeName = option
          }
        },
        {
          keyName: 'description',
          label: '问题补充',
          type: 'BaseTextarea'
        },
        {
          keyName: 'levelName',
          label: '问题级别',
          type: 'a-radio-group',
          data: [
            // 由于后端只要汉字不要id，所有没有请求枚举，枚举接口为cscec-quality-business/quality/types-label?type=40
            {
              value: '重大',
              label: '重大'
            },
            {
              value: '较大',
              label: '较大'
            },
            {
              value: '一般',
              label: '一般'
            }
          ]
        },
        {
          keyName: 'rectifyTerm',
          label: '整改期限',
          type: 'BaseInput',
          disabled: true
        },
        {
          keyName: 'rectifierId',
          label: '整改人',
          type: 'a-select',
          data: this.rectifierCompany?.rectifiers || [],
          hidden:this.isFlagcheckType, 
          replaceFields: {
            value: 'id',
            label: 'name'
          },
          change: (e) => {
            this.$refs.dialogForm.forms.rectifierName = this.rectifierCompany?.rectifiers?.find((i) => i.id === e)?.name
          }
        },
        {
          keyName: 'dutyId',
          label: '责任人',
          type: 'a-select',
          data: this.rectifierCompany?.duty || [],
          hidden:this.isFlagcheckType, 
          replaceFields: {
            value: 'id',
            label: 'name'
          },
          change: (e) => {
            this.$refs.dialogForm.forms.dutyName = this.rectifierCompany?.duty?.find((i) => i.id === e)?.name
          }
        },
        {
          keyName: 'rectifierId',      // 公司级
          label: '整改人',
          type: ASelectOrgPeople,
          hidden:!this.isFlagcheckType, 
          attrs: {
            optionKey: 'id',
            keyValue: 'inspectedUnitId', // 联动字段名
            orgId: this.dialogForm.inspectedUnitId, // 联动表单
            isRank:true,
          },
            onSelectChange: (e) => {
            this.$refs.dialogForm.forms.rectifierName = e?.name
          }
        },
        {
          keyName: 'dutyId',   // 公司级
          label: '责任人',
          type: ASelectOrgPeople,
          hidden:!this.isFlagcheckType, 
          attrs: {
            optionKey: 'id',
            keyValue: 'inspectedUnitId', // 联动字段名
            orgId: this.dialogForm.inspectedUnitId, // 联动表单
            isRank:true,
          },
          onSelectChange: (e) => {
            this.$refs.dialogForm.forms.dutyName = e?.name
          }
        },
        {
          keyName: 'reCheckId',
          label: '复查人',
          type: ASelectOrgPeople,
          hidden: !this.visible,
          attrs: {
            optionKey: 'id',
            keyValue: 'inspectedUnitId', // 联动字段名
            orgId: this.dialogForm.inspectedUnitId, // 联动表单
            isRank:true,
          }
        },
        {
          keyName: 'sendUserIds',
          label: '抄送',
          type: ASelectOrgPeople,
          hidden: !this.visible,
          attrs: {
            mode: 'multiple',
            maxTagCount: 1,
            optionKey: 'id',
            orgId: this.dialogForm.inspectedUnitId, // 联动表单
            isRank:true,
          }
        },
        {
          keyName: 'coordinate',
          label: '检查（问题）具体位置',
          slot: true
        },
        {
          keyName: 'specialTypes',
          label: '工程品质类型',
          hidden: this.$currentPost()?.code === 'PD',
          type: 'a-cascader',
          placeholder: '请选择工程品质类型',
          attrs: {
            fieldNames: { label: 'name', value: 'id', children: 'children' },
            options: this.options
          },
          change: (e, option) => {
            // console.log(e,option)
            this.$refs.dialogForm.forms.specialType = e?.[0]
            this.$refs.dialogForm.forms.specialName = option?.[1]?.name
            // console.log(this.$refs.dialogForm.forms)
          }
        },
        {
          keyName: 'fileArrays',
          label: '影像资料',
          type: 'uploadFile',
          businessCode: 'QM01',
          remark:'请上传原件，支持格式：.jpg .png .mp4 .mov',
          attrs: {
            delRequest: false,
            uploadType: 'uploadImgAndVideo',
            editModel: this.dialogEditModel,
            isMultiple: true,
            useAccept: true,
            isUploadImgAndVideo:true,
            isUploadImgAndVideoLog:true,
            accept: "'.jpg', '.jpeg', '.png', '.avi', '.wmv', '.mpg', '.mpeg', '.mov', '.rm', '.ram', '.swf', '.flv', '.mp4', '.mp3', '.wma', '.rmvb', '.mkv'"
          },
          span: 16
        }
      ]
    },
    wtjbClassName(){
       let flag = '';
       if(this.isBcRules){  //为补充
          if(this.isFlagcheckType){   //管理和资料
             flag = 'xwziClassName'
          }else{
              flag = 'stcsClassName'  // 实体和措施
          }
       }else{
        flag = '';
       }
       return flag;
    }
  },
  methods: {
    changeRules(val){
       if(val.isBcRules){  //是否是补充
          this.isBcRules = val.isBcRules;
          if(val.checkTypeName == '工程实体' || val.checkTypeName == '工程措施'){
            this.bcRules  = true;
          }else{
            this.bcRules  = true;
          }
       }else{
          this.bcRules  = false;
       }
    },
    /**
     * @description: 获取专项治理类型和新六项措施类型
     * @return {*}
     */
    async getType() {
      const options = [
        {
          id: 0,
          name: '专项治理类型',
          isLeaf: false
          // children: []
        },
        {
          id: 1,
          name: '新六项措施类型',
          isLeaf: false
          // children: []
        }
      ]
      // 获取专项治理类型
      const res = await scoringType.getList()
      if (res.code === 200 && res.data?.length) {
        options[0].children = res.data.map((i) => {
          // 后台只保存name，不需要id，所以枚举的id和name都是name
          i.id = i.name
          return i
        })
      }

      // 获取新六项措施类型
      const res2 = await office.typesLabel({ type: 44 })
      if (res2.code === 200 && res2.data?.length) {
        options[1].children = res2.data.map((i) => {
          // 后台只保存name，不需要id，所以枚举的id和name都是name
          i.id = i.name
          return i
        })
      }
      this.options = options
    },
    /**
     * @description: form：表单
     */
    handleChoose(form) {
      if (!form.respAreaId) {
        this.$message.warning('请先选择检查区域！')
        return
      }
      this.btnLoading = true
      // 先请求检查区域施工图，再打开点位图
      getNodeById(form.respAreaId)
        .then((res) => {
          if (res.code === 200 && res.data) {
            // 映射施工图到点位背景
            this.previewImage = [res.data]
            // 打开弹窗
            this.previewVisible = true
          } else {
            this.$message.warning('请先添加检查区域的施工图！')
          }
        })
        .finally(() => {
          this.btnLoading = false
        })
    },
    /**
     * @description: 转化弹窗表单检查（问题）具体位置坐标，格式化成x,y:x,y字符形式
     * @param {*} e：点位列表
     * @param {*} form：表单
     */
    handlePoints(e, form) {
      // console.log(arguments)
      if (!form.problem) {
        this.$set(form, 'problem', { coordinate: e?.map((i) => i.x + ',' + i.y)?.join(';') })
      } else {
        this.$set(form.problem, 'coordinate', e?.map((i) => i.x + ',' + i.y)?.join(';'))
      }
      this.$set(form, 'coordinate', e)
    },
    // 获取工程类别数据
    getProductType(val){
      let obj = val?{id:val}:{};
       projectType.getList(obj).then((res)=>{
         if(res.code == 200){
             this.productType = res.data.filter((item)=>item.status*1===1);
     
         }
       })
    },
    //获取工程资料或管理行为分部分项
     getSubItemData(id){
      let args = {
          sources: 0,
          id,
      }
      id && subItem.getList(args).then((res)=>{
        if(res.code == 200){
          this.fbfxTreeData = res?.data[0]?.children || [];
        }
      })
    },

  }
}
</script>
<style scoped lang="less">
@deep: ~'>>>';
.isFlagcheckType{
  @{deep} .ant-row-flex{
     .ant-col:nth-child(3), .ant-col:nth-child(6){
      .requiredFormItem{
        .ant-select{
          .ant-select-selection{
            background-color: #fff;
            border: 1px solid #d9d9d9;
          }
        }
      }
     }
  }
}
.deFlagcheckType{
  @{deep} .ant-row-flex{
     .ant-col:nth-child(4){
       .ant-select{
          .ant-select-selection{
            border-color: #e4ac0b;
            background-color: #FFF9E8;
          }
        }
     }
  }
}
.pubDialogForm{
    @{deep} .ant-row-flex{
     .ant-col:nth-child(4){
       .ant-select-selection__placeholder{
        display: block!important;
       }
     }
  }
}
.stcsClassName{
    @{deep} .ant-row-flex{
     .ant-col:nth-child(9){
      .ant-form-item-required::before{
       opacity: 1;
      }
     }
      .ant-col:nth-child(3), .ant-col:nth-child(5), .ant-col:nth-child(7), .ant-col:nth-child(8){
       .ant-select{
          .ant-select-selection{
            border-color: #e4ac0b;
            background-color: #FFF9E8;
          }
        }
     }
  }
}
.xwziClassName{
    @{deep} .ant-row-flex{
     .ant-col:nth-child(10){
      .ant-form-item-required::before{
       opacity: 1;
      }
     }
  }
}
</style>